#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QNetworkInterface>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , tcpServer(nullptr)
    , clientSocket(nullptr)
    , serial(nullptr)
    , isServerRunning(false)
{
    ui->setupUi(this);

    // 初始化TCP服务器
    tcpServer = new QTcpServer(this);
    
    // 初始化串口
    serial = new QSerialPort(this);
    
    // 填充串口列表
    const auto infos = QSerialPortInfo::availablePorts();
    for (const QSerialPortInfo &info : infos) {
        ui->serialPortCombo->addItem(info.portName());
    }
    
    // 填充波特率列表
    QList<qint32> baudRates = QSerialPortInfo::standardBaudRates();
    for (qint32 baudRate : baudRates) {
        ui->baudRateCombo->addItem(QString::number(baudRate));
    }
    ui->baudRateCombo->setCurrentText("9600");
    
    // 连接信号槽
    connect(ui->startStopButton, &QPushButton::clicked, this, &Widget::onStartStopClicked);
    connect(ui->testButton, &QPushButton::clicked, this, &Widget::onTestClicked);
    connect(tcpServer, &QTcpServer::newConnection, this, &Widget::onNewConnection);
    connect(serial, &QSerialPort::readyRead, this, [this]() {
        QByteArray data = serial->readAll();
        ui->statusBrowser->append("串口收到: " + data);
    });
    
    // 显示本机IP
    QString ipAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    for (const QHostAddress &address : ipAddressesList) {
        if (address != QHostAddress::LocalHost && address.toIPv4Address()) {
            ipAddress = address.toString();
            break;
        }
    }
    if (ipAddress.isEmpty()) {
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
    }
    ui->ipEdit->setText(ipAddress);
    
    ui->statusBrowser->append("系统初始化完成");
}

Widget::~Widget()
{
    if (tcpServer) {
        tcpServer->close();
    }
    if (serial && serial->isOpen()) {
        serial->close();
    }
    delete ui;
}

void Widget::onStartStopClicked()
{
    if (!isServerRunning) {
        // 启动服务
        QString ip = ui->ipEdit->text();
        quint16 port = ui->portEdit->text().toUShort();
        
        if (!tcpServer->listen(QHostAddress(ip), port)) {
            ui->statusBrowser->append("启动失败: " + tcpServer->errorString());
            return;
        }
        
        // 打开串口
        serial->setPortName(ui->serialPortCombo->currentText());
        serial->setBaudRate(ui->baudRateCombo->currentText().toInt());
        
        if (!serial->open(QIODevice::ReadWrite)) {
            ui->statusBrowser->append("串口打开失败: " + serial->errorString());
            tcpServer->close();
            return;
        }
        
        isServerRunning = true;
        ui->startStopButton->setText("停止服务");
        ui->statusBrowser->append(QString("服务已启动，监听 %1:%2").arg(ip).arg(port));
    } else {
        // 停止服务
        tcpServer->close();
        if (serial->isOpen()) {
            serial->close();
        }
        if (clientSocket) {
            clientSocket->close();
            clientSocket = nullptr;
        }
        
        isServerRunning = false;
        ui->startStopButton->setText("启动服务");
        ui->statusBrowser->append("服务已停止");
    }
}

void Widget::onNewConnection()
{
    if (clientSocket) {
        QTcpSocket *socket = tcpServer->nextPendingConnection();
        socket->close();
        socket->deleteLater();
        ui->statusBrowser->append("已有客户端连接，拒绝新连接");
        return;
    }
    
    clientSocket = tcpServer->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &Widget::onReadyRead);
    connect(clientSocket, &QTcpSocket::disconnected, this, &Widget::onDisconnected);
    
    ui->statusBrowser->append(QString("客户端已连接: %1:%2")
                             .arg(clientSocket->peerAddress().toString())
                             .arg(clientSocket->peerPort()));
}

void Widget::onReadyRead()
{
    if (!clientSocket) return;
    
    QByteArray data = clientSocket->readAll();
    ui->statusBrowser->append("收到指令: " + data);
    
    if (serial->isOpen()) {
        qint64 bytesWritten = serial->write(data);
        if (bytesWritten == -1) {
            ui->statusBrowser->append("串口发送失败: " + serial->errorString());
        } else {
            ui->statusBrowser->append("指令已发送到串口");
        }
    } else {
        ui->statusBrowser->append("串口未打开，无法发送指令");
    }
}

void Widget::onDisconnected()
{
    ui->statusBrowser->append("客户端已断开连接");
    clientSocket->deleteLater();
    clientSocket = nullptr;
}

void Widget::onTestClicked()
{
    if (!serial->isOpen()) {
        ui->statusBrowser->append("测试失败: 串口未打开");
        return;
    }

    QByteArray testData = "a";
    qint64 bytesWritten = serial->write(testData);
    
    if (bytesWritten == -1) {
        ui->statusBrowser->append("测试失败: " + serial->errorString());
    } else {
        ui->statusBrowser->append("已发送测试数据: " + testData);
        ui->statusBrowser->append("等待串口返回数据...");
    }
}
